<script setup lang="ts">
import {computed, reactive, ref, watch} from 'vue';
import {useFormRules, useNaiveForm} from '@/hooks/common/form';
import {$t} from '@/locales';
import {fetchAllMenu, fetchRoleMenus} from "@/service/api";
import {TreeOption} from "naive-ui";
import {fetchSaveRole, fetchUpdateRole} from "@/service/api/roles";


interface Emits {
  (e: 'submitted'): void;
}

interface Props {
  operateType: Api.Common.OperateType;
  rowData?: Api.Entity.Role | null;
}

defineOptions({
  name: 'RoleOperateDrawer'
});

const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
  default: false
});
const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule} = useFormRules();
const title = computed(() => {
  const titles: Record<Api.Common.OperateType, string> = {
    add: '添加',
    edit: '修改'
  };
  return titles[props.operateType];
});
const model: Api.Entity.Role = reactive(createDefaultModel());
const rules: Record<keyof Pick<Api.Entity.Role, 'name' | 'code'>, App.Global.FormRule> = {
  name: defaultRequiredRule,
  code: defaultRequiredRule,
};

const treeData = ref([]);
const checkedKeys = ref([]);

function createDefaultModel(): Api.Entity.Role {
  return {
    id: null,
    name: '',
    code: '',
    desc: '',
  };
}

function handleUpdateModelWhenEdit() {
  checkedKeys.value = [];
  getTreeData()
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }
  if (props.operateType === 'edit' && props.rowData) {
    getRoleMenus(props.rowData?.id || 0)
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add') {
    let {error} = await fetchSaveRole(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
    }

  }
  if (props.operateType === 'edit') {
    let {error} = await fetchUpdateRole(model);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
    }
  }
  closeDrawer();
  emit('submitted');
}

function handleTreeClick(e) {
}

async function getTreeData() {
  treeData.value = [];
  let {error, data} = await fetchAllMenu();
  if (!error) {
    //遍历树形
    const loop = (data: Api.SystemManage.Menu[]) => {
      return data.map(item => {
        return {
          label: $t(`${item.meta.i18nKey}`),
          key: item.id,
          children: item.children ? loop(item.children) : []
        }
      });
    }
    for (const any of loop(data?.routes || [])) {
      treeData.value.push(any);
    }
  }
}

async function getRoleMenus(roleId: number) {
  let {error, data} = await fetchRoleMenus(roleId);
  if (!error) {
    const loop = (data: Api.SystemManage.Menu[]) => {
      return data.map(item => {
        checkedKeys.value.push(item.id);
        if (item.children) {
          loop(item.children)
        }
      });
    }
    loop(data || [])
  }
}

function updateCheckedKeys(keys: number[], option: Array<TreeOption | null>, meta) {
  // 判断是否包含
  if (meta.action === 'check') {
    keys.push(meta.node?.key as number)
  } else {
    keys = keys.filter(item => item != meta.node?.key);
  }
  model.params = {
    menuIds: keys
  }
  checkedKeys.value = keys;
  return true
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>
<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.manage.role.roleName')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.manage.role.form.roleName')"/>
        </NFormItem>
        <NFormItem :label="$t('page.manage.role.roleCode')" path="code">
          <NInput v-model:value="model.code" :placeholder="$t('page.manage.role.form.roleCode')"/>
        </NFormItem>
        <NFormItem :label="$t('page.manage.role.roleDesc')" path="desc">
          <NInput type="textarea" v-model:value="model.desc" :placeholder="$t('page.manage.role.form.roleDesc')"/>
        </NFormItem>
        <NFormItem label="权限">
          <n-tree
            :show-line="true"
            checkable
            check-on-click
            default-expand-all
            :selectable="false"
            :data="treeData"
            @click="handleTreeClick"
            :checked-keys="checkedKeys"
            @update:checked-keys="updateCheckedKeys"
          />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
